package com.lxs;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class HostsFileReader {
    public static void main(String[] args) {
        readHostsFile();
    }

    public static void readHostsFile() {
        Path hostsPath;

        // 根据操作系统选择HOSTS文件路径
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            hostsPath = Paths.get("C:\\Windows\\System32\\drivers\\etc\\hosts");
        } else {
            hostsPath = Paths.get("/etc/hosts");
        }

        try {
            List<String> lines = Files.readAllLines(hostsPath);
            System.out.println("HOSTS文件中的域名映射:");

            for (String line : lines) {
                // 跳过注释和空行
                String trimmed = line.trim();
                if (trimmed.isEmpty() || trimmed.startsWith("#")) {
                    continue;
                }

                // 解析IP和域名
                String[] parts = trimmed.split("\\s+");
                if (parts.length >= 2) {
                    System.out.println("IP: " + parts[0] + " -> 域名: " + parts[1]);

                    // 测试解析
                    try {
                        InetAddress address = InetAddress.getByName(parts[1]);
                        System.out.println("  实际解析为: " + address.getHostAddress());
                    } catch (UnknownHostException e) {
                        System.out.println("  解析失败");
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("无法读取HOSTS文件: " + e.getMessage());
        }
    }
}
